<template>
  <div class="logs-container">
    <div class="header">
      <h2>系统日志</h2>
      <div class="header-actions">
        <el-button type="danger" @click="handleClearLogs">
          <el-icon><Delete /></el-icon>
          清空日志
        </el-button>
        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出日志
        </el-button>
      </div>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="操作">
          <el-input v-model="searchForm.action" placeholder="请输入操作" clearable />
        </el-form-item>
        <el-form-item label="资源">
          <el-input v-model="searchForm.resource" placeholder="请输入资源" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="成功" value="success" />
            <el-option label="失败" value="error" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="tableData" v-loading="loading" stripe>
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户" width="120" />
      <el-table-column prop="action" label="操作" width="120" />
      <el-table-column prop="resource" label="资源" width="120" />
      <el-table-column prop="method" label="请求方法" width="100">
        <template #default="{ row }">
          <el-tag
            :type="getMethodTagType(row.method)"
            size="small"
          >
            {{ row.method }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="url" label="请求URL" min-width="200" show-overflow-tooltip />
      <el-table-column prop="ip" label="IP地址" width="140" />
      <el-table-column prop="userAgent" label="用户代理" min-width="200" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 'success' ? 'success' : 'danger'">
            {{ row.status === 'success' ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="duration" label="耗时(ms)" width="100" />
      <el-table-column prop="createdAt" label="操作时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="日志详情" width="800px">
      <div v-if="currentLog" class="log-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ currentLog.id }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentLog.username }}</el-descriptions-item>
          <el-descriptions-item label="操作">{{ currentLog.action }}</el-descriptions-item>
          <el-descriptions-item label="资源">{{ currentLog.resource }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">
            <el-tag :type="getMethodTagType(currentLog.method)" size="small">
              {{ currentLog.method }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="请求URL">{{ currentLog.url }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ currentLog.ip }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentLog.status === 'success' ? 'success' : 'danger'">
              {{ currentLog.status === 'success' ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="耗时">{{ currentLog.duration }}ms</el-descriptions-item>
          <el-descriptions-item label="操作时间">
            {{ formatDate(currentLog.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="用户代理" :span="2">
            {{ currentLog.userAgent }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div v-if="currentLog.requestData" class="log-section">
          <h4>请求数据</h4>
          <el-input
            v-model="currentLog.requestData"
            type="textarea"
            :rows="6"
            readonly
          />
        </div>
        
        <div v-if="currentLog.responseData" class="log-section">
          <h4>响应数据</h4>
          <el-input
            v-model="currentLog.responseData"
            type="textarea"
            :rows="6"
            readonly
          />
        </div>
        
        <div v-if="currentLog.errorMessage" class="log-section">
          <h4>错误信息</h4>
          <el-alert
            :title="currentLog.errorMessage"
            type="error"
            :closable="false"
            show-icon
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Download } from '@element-plus/icons-vue'

/**
 * 系统日志接口
 */
interface SystemLog {
  id: number
  username: string
  action: string
  resource: string
  method: string
  url: string
  ip: string
  userAgent: string
  status: 'success' | 'error'
  duration: number
  requestData?: string
  responseData?: string
  errorMessage?: string
  createdAt: string
}

/**
 * 搜索表单数据
 */
const searchForm = reactive({
  username: '',
  action: '',
  resource: '',
  status: '',
  dateRange: [] as string[]
})

/**
 * 表格数据
 */
const tableData = ref<SystemLog[]>([])
const loading = ref(false)

/**
 * 分页数据
 */
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

/**
 * 详情对话框
 */
const detailDialogVisible = ref(false)
const currentLog = ref<SystemLog | null>(null)

/**
 * 格式化日期
 */
const formatDate = (date: string) => {
  return new Date(date).toLocaleString()
}

/**
 * 获取请求方法标签类型
 */
const getMethodTagType = (method: string) => {
  const typeMap: Record<string, string> = {
    GET: 'info',
    POST: 'success',
    PUT: 'warning',
    DELETE: 'danger',
    PATCH: 'warning'
  }
  return typeMap[method] || 'info'
}

/**
 * 获取系统日志列表
 */
const fetchLogs = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取系统日志列表
    // const params = {
    //   page: pagination.page,
    //   size: pagination.size,
    //   ...searchForm
    // }
    // if (searchForm.dateRange.length === 2) {
    //   params.startTime = searchForm.dateRange[0]
    //   params.endTime = searchForm.dateRange[1]
    // }
    // const response = await request.get('/api/logs', { params })
    // tableData.value = response.data.data
    // pagination.total = response.data.total
    
    // 模拟数据
    tableData.value = [
      {
        id: 1,
        username: 'admin',
        action: '用户登录',
        resource: 'auth',
        method: 'POST',
        url: '/api/auth/login',
        ip: '192.168.1.100',
        userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36',
        status: 'success',
        duration: 120,
        requestData: JSON.stringify({ username: 'admin', password: '***' }, null, 2),
        responseData: JSON.stringify({ token: '***', user: { id: 1, username: 'admin' } }, null, 2),
        createdAt: '2024-01-01T10:00:00Z'
      },
      {
        id: 2,
        username: 'user1',
        action: '创建用户',
        resource: 'user',
        method: 'POST',
        url: '/api/users',
        ip: '192.168.1.101',
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
        status: 'success',
        duration: 200,
        requestData: JSON.stringify({ username: 'newuser', email: 'newuser@example.com' }, null, 2),
        responseData: JSON.stringify({ id: 2, username: 'newuser', email: 'newuser@example.com' }, null, 2),
        createdAt: '2024-01-01T11:00:00Z'
      },
      {
        id: 3,
        username: 'user2',
        action: '删除用户',
        resource: 'user',
        method: 'DELETE',
        url: '/api/users/3',
        ip: '192.168.1.102',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
        status: 'error',
        duration: 50,
        errorMessage: '权限不足，无法删除用户',
        createdAt: '2024-01-01T12:00:00Z'
      }
    ]
    pagination.total = 3
  } catch (error) {
    ElMessage.error('获取系统日志失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  fetchLogs()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    action: '',
    resource: '',
    status: '',
    dateRange: []
  })
  pagination.page = 1
  fetchLogs()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.size = size
  fetchLogs()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchLogs()
}

/**
 * 查看详情
 */
const handleViewDetail = (row: SystemLog) => {
  currentLog.value = row
  detailDialogVisible.value = true
}

/**
 * 清空日志
 */
const handleClearLogs = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有系统日志吗？此操作不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // TODO: 调用API清空日志
    // await request.delete('/api/logs/clear')
    
    ElMessage.success('清空日志成功')
    fetchLogs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('清空日志失败')
    }
  }
}

/**
 * 导出日志
 */
const handleExport = async () => {
  try {
    // TODO: 调用API导出日志
    // const response = await request.get('/api/logs/export', {
    //   params: searchForm,
    //   responseType: 'blob'
    // })
    // const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
    // const url = window.URL.createObjectURL(blob)
    // const link = document.createElement('a')
    // link.href = url
    // link.download = `系统日志_${new Date().toISOString().slice(0, 10)}.xlsx`
    // link.click()
    // window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出日志成功')
  } catch (error) {
    ElMessage.error('导出日志失败')
  }
}

onMounted(() => {
  fetchLogs()
})
</script>

<style scoped>
.logs-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.search-form {
  margin: 0;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.log-detail {
  max-height: 600px;
  overflow-y: auto;
}

.log-section {
  margin-top: 20px;
}

.log-section h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}
</style>